import React, { Component } from 'react';
import PropTypes from "prop-types";
import {
    Text,
    View,
    StyleSheet,
    Image,
    Modal,
    TouchableOpacity,
    Dimensions,
    Platform
} from 'react-native';

import ProgressCircle from './ProgressCircle.js';
import Font from '../../config/theme/standard/fonts.js';
import Color from '../../config/theme/standard/color.js';

import Label from '../label/index';


const {height,width}=Dimensions.get('window')
export default class Progress extends Component {

    constructor(props){
        super(props);
        this.state = {
            prevPropsModalVisible: props.isShow,
            modalVisible: props.isShow,
            isWideScreen: false, // 鸿蒙适配是否宽屏
        }
    }
    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        const {percent,modalTitle}=nextProps
        if (('isShow' in nextProps) && (nextProps.isShow !== prevState.prevPropsModalVisible)) {
            return {
                percent,
                prevPropsModalVisible: nextProps.isShow,
                modalVisible: nextProps.isShow,
            }; 
        }
        if(percent===100) {
            return  { 
            modalVisible: false,
            modalTitle:nextProps.modalTitle
        }
        }
        return null;
    }

    // 关闭模态框
    _close = () => {
        if(typeof this.props.onClose == 'function'){
            this.props.onClose()
        }
        this.setState({
            modalVisible: false
        });
    }
    // 安卓返回键关闭（apple TV菜单键）
    _onRequestClose(){
        this.setState({
            modalVisible: false
        });
    }
    render(){
        const props = this.props;
        const {
            percent = 0,
            status,
            format,
            size,
            type,
            strokeWidth,
            showInfo,
            bgcolor,
            children,
            containerStyle,
            isModal,
            isShow,
            modalTitle,
            onClose,
            modalClosebtn,
            modalbgcolor,
            modalopacity,
            ModalClose,
            ...restProps
        } = props;

        const progressStatus = parseInt(percent.toString(), 10) >= 100 && !('status' in props) ?
            'success' : (status || 'normal');

        let backgroundColor;
        let progressInfo;
        let progress;
        let themeColor = bgcolor || Color.main;

        switch (progressStatus){
            case 'normal':
                backgroundColor = isModal ? type=='circle' ?  themeColor : '#fff' : themeColor;
                break;
            case 'success':
                backgroundColor = isModal ? '#fff' : themeColor;
                break;
            case 'exception':
                backgroundColor = Color.label.error;
                break;
            default:
                backgroundColor = bgcolor;
        }
        // 文本进度值百分比格式
        const textFormatter = format || (percentNumber => `${percentNumber}%`);
        // 进度条信息
        if (showInfo) {
            let text;
            if (progressStatus === 'exception') {
                text = format ? textFormatter(percent) :
                    <Image style={styles.imageLine} source={require('../../assets/progress_exception.png')}/>;
            } else if (progressStatus === 'success') {
                text = format ? textFormatter(percent) : textFormatter(percent)
            } else {
                text = textFormatter(percent);
            }
            progressInfo = (
                <View style={styles.progressLineContainer}>
                    <Label labelStyle={[styles.progressText, {color: isModal ? '#fff' : themeColor, fontSize: 15}]} text={text} />
                </View>
            )
        }
        if (type === 'line') {
            const percentStyle = {
                width: `${percent}%`,
                height: strokeWidth || (size === 'small' ? 6 : 8),
            };
           
            let modalTitleView = isModal ?
                <View style={{flex: 1, flexDirection: 'row'}}>
                    <View style={{flex: 1}}></View>
                    <Label labelStyle={[{flex: 1, textAlign: 'center', color: '#fff', fontSize: 15, marginTop: 8}]} text={modalTitle}/>
                    <TouchableOpacity
                        activeOpacity={0.9}
                        onPress={this._close}
                        style={{alignItems: 'flex-end', flex: 1, opacity: modalClosebtn ? 0.9 : 0, marginTop: 10, marginRight: 10}}
                    >
                        <Image style={styles.imageClose} source={require('../../assets/progress_close.png')}/>
                    </TouchableOpacity>
                </View>: null
                progress = (
                    <View style={{flex: 1}}>
                        {modalTitleView}
                        <View style={styles.progressOuter}>
                            <View style={[styles.progressInner, {backgroundColor: isModal ? '#666' : '#d8d8d8'}]}>
                                <View style={[styles.progressBg, percentStyle,
                                    {backgroundColor: backgroundColor}]}></View>
                            </View>
                        </View>
                        {progressInfo}
                    </View>
                );
        } else if (type === 'circle') {
            let childrenText;
            switch (progressStatus){
                case 'success':
                    childrenText = <Image style={styles.imageCircle} source={require('../../assets/progress_correct.png')}/>;
                    break;
                case 'exception':
                    childrenText = <Image style={styles.imageCircle} source={require('../../assets/progress_error.png')}/>;
                    break;
                default:
                    childrenText = children;
            }
            let modalTitleView = isModal ?
                <View style={{flex: 1, flexDirection:'row'}}>
                    <View style={{flex: 1}}></View>
                    <Label labelStyle={[{flex: 1, textAlign: 'center', color: '#fff', fontSize: 15, marginTop: 12}]} text={modalTitle}/>
                    <TouchableOpacity
                        activeOpacity={0.9}
                        onPress={this._close}
                        style={{ alignItems: 'flex-end', flex: 1, opacity: modalClosebtn ? 1:0, marginTop: 10, marginRight: 10}}
                    >
                        <Image style={styles.imageClose} source={require('../../assets/progress_close.png')}/>
                    </TouchableOpacity>
                </View> : null
            progress = (
                <View style={{flex: 1, justifyContent: 'center', alignItems:'center'}}>
                    {modalTitleView}
                    <ProgressCircle {...restProps}
                        color={backgroundColor}
                        percent={percent}
                        borderWidth={strokeWidth}
                        children={childrenText}>
                    </ProgressCircle>
                </View>
            );
        }

        if(isModal){
            return (
                <Modal animationType='none'
                    // 背景是否透明，默认白色
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={()=>this._onRequestClose()}>
                    {/* 遮罩层 */}
                    <TouchableOpacity onPress={ModalClose ? (this._close) : null} activeOpacity={1}>
                        {/* 鸿蒙适配宽度 width: Dimensions.get('window').width */}
                        <View style={{ height, width: Dimensions.get('window').width, backgroundColor: modalbgcolor, opacity: modalopacity }}>
                            {/* 鸿蒙适配宽度 width: Dimensions.get('window').width - 130 */}
                            <View style={[type == 'circle' ? styles.circleContainer : styles.container, containerStyle, { width: Dimensions.get('window').width - 130 }, Platform.OS == 'harmony' &&{ zIndex:1 }]}>
                                <View style={type === 'line' ? [styles.progressLine, { borderRadius: 5, height: 87 }, containerStyle] : [{ height: 150 }, containerStyle]}>
                                    {progress}
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>
            )
        } else {
            return (
                <View style={type === 'line'? [styles.progressLine, {width: Dimensions.get('window').width-125}, containerStyle]:['',containerStyle]}>
                    {progress}
                </View>
            )
        }

    }
}

Progress.propTypes = {
    status: PropTypes.oneOf(['normal', 'exception', 'success']),
    type: PropTypes.oneOf(['line', 'circle']),
    showInfo: PropTypes.bool,   //进度条信息
    percent: PropTypes.number,   //进度条百分比
    strokeWidth: PropTypes.number,  //直线进度条宽度
    format: PropTypes.func,    //直线进度条文本格式
    bgcolor: PropTypes.string,
    size: PropTypes.oneOf(['default', 'small']),
    containerStyle: PropTypes.any,
    isModal: PropTypes.bool,  // 模态框显示隐藏
    isShow: PropTypes.bool, //与isModal配套使用，用于模态进度条的展示与否
    modalTitle: PropTypes.string,
    modalClosebtn:PropTypes.bool, //模态框关闭按钮是否隐藏
    modalbgcolor:PropTypes.string,//模态框背景
    modalopacity:PropTypes.number ,//模态框透明度
    ModalClose:PropTypes.bool //点击遮罩层关闭模态框 false失效
};
Progress.defaultProps = {
    type: 'line',
    percent: 75,
    showInfo: true,
    size: 'small',
    isModal: false,
    isShow: false,
    modalTitle: '',
    width: 254,
    //containerStyle: {height: 87, width: Dimensions.get('window').width-130, borderWidth: 1},
    bgcolor:'#FA5050',
    strokeWidth:6,
    modalClosebtn:true,
    modalbgcolor:'#666',
    modalopacity:0.8,
    color:'#fff',
    ModalClose:true
};
const styles = StyleSheet.create({
    progressOuter:{
        flex: 1,
        justifyContent: 'center',
        paddingHorizontal: 28,
    },
    progressInner: {
        //backgroundColor: '#f3f3f3',
        borderRadius: 100
    },
    imageClose:{
        width: 12,
        height: 12,
        resizeMode: 'cover'
    },
    progressLineContainer:{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    progressBg:{
        borderRadius: 100
    },
    progressText: {
        flex: 1,
        fontSize: Font.btnFontSize
    },
    progressLine: {
        height: 60,
        //borderRadius: 5,
        //marginTop:5,
        //marginRight:8,
        //marginLeft:8
    },
    imageLine:{
        width: 14,
        height: 14
    },
    imageCircle:{
        width: 32,
        height: 32
    },
    container: {
        position: 'absolute', 
        width: Dimensions.get('window').width-130,
        height: 87,
        borderRadius: 5,
        left: 130 / 2,
        top: (Dimensions.get('window').height - 100) / 2,
        backgroundColor: 'rgba(0, 0, 0, 0.4)'
    },
    circleContainer: {
        position: 'absolute', 
        width: Dimensions.get('window').width-130,
        height: 170,
        borderRadius: 5,
        left: 130 / 2,
        top: (Dimensions.get('window').height - 170) / 2,
        backgroundColor: 'rgba(0, 0, 0, 0.4)'
    }
});